package com.sgb.knowledgeshare.view.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.SurfaceTexture;
import android.text.TextUtils;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.widget.TextView;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import com.aliyun.player.AliPlayer;
import com.aliyun.player.AliPlayerFactory;
import com.aliyun.player.IPlayer;
import com.aliyun.player.bean.ErrorInfo;
import com.aliyun.player.source.UrlSource;
import com.sgb.knowledgeshare.R;
import com.sgb.knowledgeshare.databinding.ActivityShareSharelandBinding;
import com.sgb.knowledgeshare.entity.VideoReceiveListEntity;
import com.sgb.knowledgeshare.viewmodel.ShareLandModel;
import com.sgb.knowledgeshare.weight.CommentDialog;
import com.sgb.knowledgeshare.weight.CommentSendDialog;
import com.sgb.knowledgeshare.weight.LikeView;
import com.swgk.core.base.AppActivity;
import com.swgk.core.base.model.entity.VideoBean;
import com.sgb.knowledgeshare.utils.OnVideoControllerListener;
import com.swgk.core.dialog.RoundCornerDialog;
import com.sgb.knowledgeshare.weight.ShareDialog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

/**
 * Created by：PC0033 on 2020/9/28 17:46
 * 单个视频播放界面
 */
public class ShareLandActivity extends AppActivity {
    private static final String VIDEOID = "videoid";
    private static final String TYPE = "type";
    private static final String VIDEOIINFO = "";
    private ActivityShareSharelandBinding binding;
    private String video_id;
    ShareLandModel viewModel;
    private VideoReceiveListEntity.RecordsBean commentBean;
    private String type;
    private AliPlayer aliPlayer;
    private boolean  videostart;
    private VideoBean videobean;

    public static void start(Context context, String videoid, String type, VideoReceiveListEntity.RecordsBean bean) {
        Intent intent = new Intent();
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra(VIDEOID, videoid);
        intent.putExtra(TYPE, type);
        intent.putExtra(VIDEOIINFO, bean);
        intent.setClass(context, ShareLandActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_share_shareland);
        viewModel = new ViewModelProvider(this).get(ShareLandModel.class);
        viewModel.setActivity(ShareLandActivity.this);
        View decor = getWindow().getDecorView();
        decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        binding.ivBack.setOnClickListener(this);
        type = getIntent().getStringExtra(TYPE);
        video_id = getIntent().getStringExtra(VIDEOID);
        viewModel.getPlayUrl(video_id);
    }

    @Override
    protected void init() {
        aliPlayer = AliPlayerFactory.createAliPlayer(getActivity());
        binding.textureview.setSurfaceTextureListener(new TextureView.SurfaceTextureListener() {
            @Override
            public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
                Surface mSurface = new Surface(surface);
                if (aliPlayer != null) {
                    aliPlayer.setSurface(mSurface);
                    aliPlayer.redraw();
                }
            }

            @Override
            public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
                if (aliPlayer != null) {
                    aliPlayer.redraw();
                }
            }

            @Override
            public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
                if(aliPlayer != null){
                    aliPlayer.setSurface(null);
                }
                return true;
            }

            @Override
            public void onSurfaceTextureUpdated(SurfaceTexture surface) {

            }
        });
        //出错事件
        aliPlayer.setOnErrorListener(new IPlayer.OnErrorListener() {
            @Override
            public void onError(ErrorInfo errorInfo) {
            }
        });
        //准备成功事件
        aliPlayer.setOnPreparedListener(new IPlayer.OnPreparedListener() {
            @Override
            public void onPrepared() {
                //封面和按钮处理
                binding.ivPlays.setVisibility(View.GONE);
                aliPlayer.start();
                videostart= true;
            }
        });
        binding.likeviews.setOnLikeListener(new LikeView.OnLikeListener() {
            @Override
            public void onLikeListener() {
                if (videobean.isLiked()) {
                    binding.controllers.like();//点赞的状态
                } else {
                    //点赞
                    viewModel.setLike(videobean.getVideoId() + "");
                    setShuangJiDianZan(videobean);
                }
            }
        });
        binding.likeviews.setOnPlayPauseListener(() -> {
            if (videostart) {
                aliPlayer.pause();
                videostart = false;
                binding.ivPlays.setVisibility(View.VISIBLE);
            } else {
                aliPlayer.start();
                videostart = true;
                binding.ivPlays.setVisibility(View.GONE);

            }
        });
    }

    private void setShuangJiDianZan(VideoBean videobean) {
        if (videobean.isLiked()) {
            int laudCountd = videobean.getLaudCount();
            if (laudCountd>0){
                laudCountd--;
            }
            videobean.setLaudCount(laudCountd);
            videobean.setLiked(false);
        }else {
            int laudCountd = videobean.getLaudCount();
            laudCountd++;
            videobean.setLaudCount(laudCountd);
            videobean.setLiked(true);
        }
        binding.controllers.like();
        binding.controllers.setVideoData(videobean, getActivity(),true);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_back) {//返回
            finish();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (aliPlayer!=null){
            //开始播放
            aliPlayer.start();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        //停止播放
        aliPlayer.stop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //释放。释放后播放器将不可再被使用。
        aliPlayer.release();
    }

    public void setPlayUrl(VideoBean data) {
        if (data == null) {
            return;
        }
        if (data.getIsLaud() == 0) {// 是否点赞（0：不是，1：是）
            data.setLiked(false);
        } else {
            data.setLiked(true);
        }
        this.videobean = data;
        binding.controllers.setVideoData(videobean, this,true);
        //评论点赞事件
        likeShareEvent();
        //设置播放源
        UrlSource urlSource = new UrlSource();
        urlSource.setUri(data.getPlayUrl());
        aliPlayer.setDataSource(urlSource);
        aliPlayer.setLoop(true);
        //准备播放
        aliPlayer.prepare();

        commentBean = (VideoReceiveListEntity.RecordsBean) getIntent().getSerializableExtra(VIDEOIINFO);
        if (type.equals("comment")) {
            //当为评论时，判断评论是否被删除，commentBean.getIsDeleted()==1位删除状态，则不自动打开弹窗，
            if (commentBean.getIsDeleted()!=1){
                //评论和点赞的视频处理
                onDialogViewShow(data);
            }
        }else {
            onDialogViewShow(data);
        }

    }

    //评论点赞事件
    private void likeShareEvent() {
        binding.controllers.setListener(new OnVideoControllerListener() {
            //            点击头像的事件处理
            @Override
            public void onHeadClick(VideoBean videoData) {
                if (videoData.getCreateUser().equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, ""))) {
                    finish();
                } else {
                    ShareUserActivity.start(getActivity(), videoData.getCreateUser());
                }
            }

            //评论
            @Override
            public void onCommentClick(VideoBean videoData) {
                onDialogViewShow(videoData);
            }

            //直评实现
            @Override
            public void onCommentSend(VideoBean videoBean) {
                new CommentSendDialog(ShareLandActivity.this,videoBean).setCommentsucceed(new CommentSendDialog.CommentSucceed() {
                    @Override
                    public void OnCommentNumber() {
                        viewModel.getCommentNum(videoBean);
                    }
                });
            }
            //标签跳转
            @Override
            public void onLabelClickListener(VideoBean videoData) {
                LabelDetailsActivity.start(getApplicationContext(),videoData.getLabelName(),videoData.getLabelNo());
            }

            //点赞
            @Override
            public void onLikeClick(VideoBean data) {
                viewModel.setLike(data.getVideoId() + "");
                setDianZan(data.getVideoId(),data);
            }


            //            点击分享的事件处理
            @Override
            public void onShareClick(VideoBean videoData) {
                new ShareDialog(ShareLandActivity.this, 1, videoData).setOnDeleteVideo(new ShareDialog.OnDeleteVideo() {
                    @Override
                    public void OnDeleteVideoData(int Id) {
                        DeleteVideo(Id);
                    }
                });
            }

            //         点击头像下面的+号事件处理
            @Override
            public void onFocusClick(VideoBean videoData) {
                if (SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.USER_NO, "").equals(videoData.getCreateUser())) {
                    MToast.showToast(getActivity(), "不能关注自己的视频");
                }
            }
        });
    }

    private void onDialogViewShow(VideoBean videoData) {
        if (type.equals("comment")) {
            if (commentBean.getIsDeleted()!=1){
                //为评论跳转过来的
                new CommentDialog(ShareLandActivity.this, videoData, commentBean.getId(), 2, 1).setonDialog(new CommentDialog.HiedDialog() {
                    @Override
                    public void onhiedDialog() {
                        viewModel.getCommentNum(videoData);
                    }
                });
            }else {
                //为评论跳转过来的
                new CommentDialog(ShareLandActivity.this, videoData,"0", 1, 1).setonDialog(new CommentDialog.HiedDialog() {
                    @Override
                    public void onhiedDialog() {
                        viewModel.getCommentNum(videoData);
                    }
                });
            }

        } else {
            //为点赞跳转过来的
            if (!TextUtils.isEmpty(commentBean.getCommentId())) {
                new CommentDialog(ShareLandActivity.this, videoData, commentBean.getCommentId(), 2, 2).setonDialog(new CommentDialog.HiedDialog() {
                    @Override
                    public void onhiedDialog() {
                        if (videoData != null) {
                            viewModel.getCommentNum(videoData);
                        }
                    }
                });
            }
        }
    }

    //    删除视频的操作
    private void DeleteVideo(int id) {
        View view = View.inflate(getActivity(), R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        roundCornerDialog.show();
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        TextView tv_message = view.findViewById(R.id.tv_message);
        TextView tv_logout_confirm = view.findViewById(R.id.tv_logout_confirm);
        TextView tv_logout_cancel = view.findViewById(R.id.tv_logout_cancel);
        tv_message.setText("您的作品将被永久删除，无法找回。确认删除？");
        //确定
        tv_logout_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //删除视频的操作逻辑
                roundCornerDialog.dismiss();
                viewModel.deleteMyVideo(id);
            }
        });
        //取消
        tv_logout_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                roundCornerDialog.dismiss();
            }
        });
    }

    //删除完视频后重新加载视频数据
    public void setDataList() {
        finish();
    }

    private void setDianZan(String videoId, VideoBean data) {
        if (videoId.equals(data.getVideoId())) {
            if (data.isLiked()) {//为点赞
                int laudCountq = data.getLaudCount();
                if (laudCountq != 0) {
                    laudCountq--;
                }
                data.setLiked(false);
                data.setLaudCount(laudCountq);
            } else {
                int laudCountd = data.getLaudCount();
                laudCountd++;
                data.setLaudCount(laudCountd);
                data.setLiked(true);
            }
            binding.controllers.like();
            binding.controllers.setVideoData(data, getApplicationContext(),true);
        }
    }
    public void setCommentNum(VideoBean videoData) {
        binding.controllers.setVideoData(videoData, getApplicationContext(),true);
    }
}
